package org.itzheng.myrxframe.realize.apk.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

/**
 * Title:app包安装或删除的静态广播<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2019-4-17.
 */
public class PackageReceiver extends BroadcastReceiver {
    private static final String TAG = "PackageReceiver";


    // 复写onReceive()方法
    // 接收到广播后，则自动调用该方法
    @Override
    public void onReceive(Context context, Intent intent) {
        //写入接收广播后的操作
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
            String pkgName = intent.getDataString().substring(8);
            Log.w(TAG, "ACTION_PACKAGE_ADDED: " + pkgName);
            if (mListener != null) {
                mListener.onPackageChange(ChangeType.ADDED, pkgName);
            }
        } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
            String pkgName = intent.getDataString().substring(8);
            Log.w(TAG, "ACTION_PACKAGE_REMOVED: " + pkgName);
            if (mListener != null) {
                mListener.onPackageChange(ChangeType.REMOVED, pkgName);
            }
        }
    }

    /**
     * 设置变化监听
     *
     * @param listener
     */
    public PackageReceiver setOnPackageChangeListener(OnPackageChangeListener listener) {
        mListener = listener;
        return this;
    }

    /**
     * 注册广播，其实就创建一个新的广播
     *
     * @param context
     * @return
     */
    public static PackageReceiver register(Context context) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addDataScheme("package");
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        PackageReceiver packageReceiver = new PackageReceiver();
        context.registerReceiver(packageReceiver, intentFilter);
        return packageReceiver;
    }

    /**
     * 移除监听
     *
     * @param context
     * @param packageReceiver
     * @return
     */
    public static PackageReceiver unregister(Context context, PackageReceiver packageReceiver) {
        if (packageReceiver != null) {
            context.unregisterReceiver(packageReceiver);
        }
        return null;
    }

    OnPackageChangeListener mListener;

    public interface OnPackageChangeListener {
        /**
         * @param changeType 变化类型
         * @param pkgName    变化的包名
         */
        void onPackageChange(ChangeType changeType, String pkgName);
    }

    public enum ChangeType {
        ADDED, REMOVED
    }
}
